<template>
  <view class="relative">
    <wd-checkbox :modelValue="modelValue" @change="handleChange">
      请勾选并仔细阅读
      <text class="text-[#0780d8]" @click.stop="togglePrivacy(true)">《用户隐私保护》</text>
      协议
    </wd-checkbox>

    <wd-popup v-model="showPrivacy" custom-style="border-radius:16rpx;width:90%">
      <view class="text-base font-bold text-center pt-4">
        {{ privacyContractName }}
      </view>
      <view class="p-3 text-sm leading-relaxed">
        亲爱的用户，感谢您信任并使用《用户隐私保护》！我们非常重视用户的隐私和个人信息保护,
        您在使用我们的产品或服务时，我们可能收集或使用您个人信息的情形，详见
        <text class="text-[#0780d8]" @click="handleOpenPrivacyContract">
          {{ privacyContractName }}
        </text>
        全文， 请您认真阅读并充分理解，如您同意我们的政策内容，请点击同意并继续使用本软件。
      </view>

      <view class="flex justify-center gap-x-4 pb-4">
        <wd-button plain hairline :round="false" @click="handleCancel">取消</wd-button>
        <wd-button
          :round="false"
          open-type="agreePrivacyAuthorization"
          @agreeprivacyauthorization="handleAgreePrivacyAuthorization"
        >
          同意并继续
        </wd-button>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
})
const emit = defineEmits(['update:modelValue'])
const showPrivacy = ref(false)
const privacyContractName = ref('')

function handleOpenPrivacyContract() {
  // 打开隐私协议页面
  wx.openPrivacyContract({
    success: (res) => {
      console.log(res, '打开系诶')
    }, // 打开成功
    fail: () => {}, // 打开失败
    complete: () => {},
  })
}

function togglePrivacy(bol) {
  showPrivacy.value = bol
}

function handleCancel() {
  togglePrivacy(false)
  emit('update:modelValue', false)
}

function handleChange({ value }) {
  wx.getPrivacySetting({
    success: (res) => {
      privacyContractName.value = res.privacyContractName
      if (res.needAuthorization) {
        // 需要弹出隐私协议
        togglePrivacy(true)
      } else {
        emit('update:modelValue', value)
        // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
        // wx.getUserProfile()
        // wx.chooseMedia()
        // wx.getClipboardData()
        // wx.startRecord()
      }
    },
    fail: () => {},
    complete: () => {},
  })
}

function handleAgreePrivacyAuthorization(e) {
  togglePrivacy(false)
  emit('update:modelValue', true)
}

onLoad(() => {
  wx.getPrivacySetting({
    success: (res) => {
      privacyContractName.value = res.privacyContractName
    },
    fail: () => {},
    complete: () => {},
  })
})
</script>

<style lang="scss" scoped></style>
